package com.zbkj.admin.controller.publicly;

import com.alibaba.fastjson.JSON;
import com.zbkj.common.annotation.CustomResponseAnnotation;
import com.zbkj.common.result.CommonResult;
import com.zbkj.service.service.PayCallbackService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;


/**
 * 支付回调
 * +----------------------------------------------------------------------
 * | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
 * +----------------------------------------------------------------------
 * | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
 * +----------------------------------------------------------------------
 * | Author: CRMEB Team <admin@crmeb.com>
 * +----------------------------------------------------------------------
 */
@Slf4j
@RestController
@RequestMapping("api/publicly/payment/callback")
@Api(tags = "支付回调控制器")
@CustomResponseAnnotation
public class PayCallbackController {

    @Autowired
    private PayCallbackService callbackService;


    @ApiOperation(value = "微信支付回调")
    @RequestMapping(value = "/wechat")
    public String weChat(HttpServletRequest request) {
        String data = null;

        StringBuilder body = new StringBuilder();
        String line;
        try (java.io.BufferedReader reader = request.getReader()) {
            while ((line = reader.readLine()) != null) {
                body.append(line);
            }
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
        log.info("请求体内容: {}", body.toString());
        Map<String, Object> resultMap = null;
        try {
            Map<String, Object>   map = parse(body.toString());
            resultMap = (Map<String, Object>) map.get("data");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        // 验签参数
        data = resultMap.toString();
        String sign = request.getParameter("sign");
        log.info("data:{}", data);
        log.info("sign:{}", sign);

        String response = callbackService.wechatPayCallback(resultMap);
        log.info("微信支付回调 response ===> " + response);
        return response;

    }

    @ApiOperation(value = "支付宝支付回调 ")
    @RequestMapping(value = "/alipay", method = RequestMethod.POST)
    public String aliPay(HttpServletRequest request){
        //支付宝支付回调
        System.out.println("支付宝支付回调 request ===> " + JSON.toJSONString(request.getParameterMap()));
        return callbackService.aliPayCallback(request);
    }

    /**
     * 微信退款回调
     */
    @ApiOperation(value = "微信退款回调")
    @RequestMapping(value = "/wechat/refund", method = RequestMethod.POST)
    public String weChatRefund(@RequestBody String request) {
        System.out.println("微信退款回调 request ===> " + request);
        String response = callbackService.weChatRefund(request);
        System.out.println("微信退款回调 response ===> " + response);
        return response;
    }

    public Map<String, Object> parse(String input) throws UnsupportedEncodingException {
        Map<String, Object> result = new HashMap<>();
        String decodedInput = URLDecoder.decode(input, "UTF-8");

        Arrays.stream(decodedInput.split("&"))
                .forEach(param -> {
                    String[] pair = param.split("=", 2);
                    String key = pair[0];
                    String value = (pair.length == 2) ? pair[1] : "";

                    // 如果是 JSON 格式的字段（如 data），解析为 Map
                    if ("data".equals(key)) {
                        try {
                            Map<String, Object> dataMap = JSON.parseObject(value, Map.class);
                            result.put(key, dataMap);
                        } catch (Exception e) {
                            result.put(key, value); // 解析失败则保留原始字符串
                        }
                    } else {
                        result.put(key, value);
                    }
                });

        return result;
    }
}



